<?php namespace Phpcmf\Controllers;

class Order extends \Phpcmf\Home\Module {

    public $config;
    public $address;

    public function __construct(...$params) {
        parent::__construct(...$params);
        $mid = dr_safe_filename(\Phpcmf\Service::L('input')->get('mid'));
        if (!$mid) {
            $this->_msg(0, dr_lang('模块参数mid不能为空'));
        }

        $this->_module_init($mid);

        $this->config = \Phpcmf\Service::M('app')->get_config(APP_DIR);
        if (!isset($this->config['module'][$mid]['open']) || !$this->config['module'][$mid]['open']) {
            $this->_msg(0, dr_lang('模块[%s]没有开启订单权限', $this->module['name']));
        } elseif (!$this->uid && (!isset($this->config['order']['guest']) || !$this->config['order']['guest'])) {
            $this->_msg(0, dr_lang('需要登录之后才能购买'));
        }

        // 默认收货地址
        if ($this->config['module'][$this->module['dirname']]['shipping']) {
            $this->address = [
                'city' => 0,
                'address' => '',
                'name' => $this->member['name'],
                'phone' => $this->member['phone'],
            ];
        }

        \Phpcmf\Service::V()->module($mid);
    }

    // 获取商品数据
    private function _get_shop_info($data, $sku, $num) {

        return [
            'id' => $data['id'],
            'url' => $data['url'],
            'uid' => $data['uid'],
            'username' => $data['author'],
            'title' => $data['title'],
            'thumb' => $data['thumb'],
            'price' => $data['price'],
            'sn' => $data['sn'],
            'sku_name' => $data['sku_name'],
            'sku_string' => $data['sku_string'],
            'sku_value' => $sku,
            'quantity' => (int)$num,
        ];
    }

    // 订单随机编号
    private function _get_order_sn() {

        mt_srand((double) microtime() * 1000000);

        return strtoupper($this->module['dirname']).date('Ymd').str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    }


    // 获取付款方式
    private function _get_pay_type() {

        $pay_type = [];
        if ($this->uid) {
            $pay_default = 'finecms';
            $pay_type['finecms'] = require ROOTPATH.'api/pay/finecms/config.php';
        }

        if ($this->member_cache['payapi']) {
            foreach ($this->member_cache['payapi'] as $name => $t) {
                if (!is_file(ROOTPATH.'api/pay/'.$name.'/config.php')) {
                    continue; // 排除是否存在配置文件
                } elseif (!$this->uid && in_array($name, ['meet', 'remit'])) {
                    continue;
                }
                $pay_type[$name] = require ROOTPATH.'api/pay/'.$name.'/config.php';
                if (!$pay_default) {
                    $pay_default = $name;
                }
            }
        }

        return [$pay_type, $pay_default];
    }

    // 获取客户端来源 1电脑 2手机 3微信
    private function _get_agent_name() {

        if (IS_PC) {
            return 1;
        } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            return 3;
        }

        return 2;
    }

	// 直接付款
	public function buy() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        if (!$id) {
            $this->_msg(0, dr_lang('商品id参数不存在'));
        }

        $num = max(1, (int)\Phpcmf\Service::L('input')->get('num'));
        $sku = dr_safe_replace(\Phpcmf\Service::L('input')->get('sku'), 'undefined');

        $rt = \Phpcmf\Service::M('cart', 'order')->get_module_row($this->module['dirname'], $id, $sku);
        if (!$rt['code']) {
            $this->_msg(0, $rt['msg']);
        } elseif ($this->config['module'][$this->module['dirname']]['quantity'] && !$rt['data']['quantity']) {
            $this->_msg(0, dr_lang('该商品【%s】已销售完', $rt['data']['title']));
        } elseif ($this->config['module'][$this->module['dirname']]['quantity'] && $rt['data']['quantity'] < $num) {
            $this->_msg(0, dr_lang('该商品【%s】库存不足，商品剩余：%s', $rt['data']['title'], $rt['data']['quantity']));
        }

        $list = [
            $this->_get_shop_info($rt['data'], $sku, $num),
        ];

        $total = $rt['data']['price'] * $num;

        $this->_checkout($list, $total);
    }

	// 购物车的确认结算
	public function checkout() {

        $id = dr_safe_replace(\Phpcmf\Service::L('input')->get('id'));
        if (!$id) {
            $this->_msg(0, dr_lang('订单失效，请重新下单'));
        }

        $arr = [];
        $ids = explode(',', $id);
        foreach ($ids as $i) {
            $i = intval($i);
            if ($i) {
                $arr[] = $i;
            }
        }
        if (!$arr) {
            $this->_msg(0, dr_lang('订单失效，请重新下单'));
        }

        $cart = \Phpcmf\Service::M()->table(SITE_ID.'_order_cart')->where('mid', $this->module['dirname'])->where_in('id', $arr)->getAll();
        if (!$cart) {
            $this->_msg(0, dr_lang('购物车中商品无效'));
        }

        $cid = [];
        $list = [];
        $total = 0; //总价
        foreach ($cart as $t) {
            $rt = \Phpcmf\Service::M('cart', 'order')->get_module_row($this->module['dirname'], $t['cid'], $t['sku_value']);
            if (!$rt['code']) {
                $this->_msg(0, $rt['msg']);
            } elseif ($this->config['module'][$this->module['dirname']]['quantity'] && !$rt['data']['quantity']) {
                $this->_msg(0, dr_lang('该商品【%s】已销售完', $rt['data']['title']));
            } elseif ($this->config['module'][$this->module['dirname']]['quantity'] && $rt['data']['quantity'] < $t['quantity']) {
                $this->_msg(0, dr_lang('该商品【%s】库存不足，商品剩余：%s', $rt['data']['title'], $rt['data']['quantity']));
            }
            $cid[] = $t['id'];
            $total+= $rt['data']['price'] * $t['quantity'];
            $list[] = $this->_get_shop_info($rt['data'], $t['sku_value'], $t['quantity']);
        }

        $this->_checkout($list, $total, $cid);
    }



    // 确认结算
    public function _checkout($list, $total, $cart = []) {

        // 付款方式
        list($pay_type, $pay_default) = $this->_get_pay_type();

        $field = \Phpcmf\Service::M('order', 'order')->get_field($this->config, $this->module['dirname']);

        // 提交订单
        if (IS_POST) {
            $post = \Phpcmf\Service::L('input')->post('data', true);
            // 收货地址
            if ($this->config['module'][$this->module['dirname']]['shipping']) {
                if (!$post['name']) {
                    $this->_json(0, dr_lang('收货人姓名未填写'), ['field' => 'name']);
                } elseif (!$post['phone']) {
                    $this->_json(0, dr_lang('收货人电话未填写'), ['field' => 'phone']);
                } elseif (!$post['city']) {
                    $this->_json(0, dr_lang('收货人城市未填写'), ['field' => 'city']);
                } elseif (!$post['address']) {
                    $this->_json(0, dr_lang('收货人详细地址未填写'), ['field' => 'address']);
                }
                $post['address'] = dr_linkagepos('address', $post['city'], '', '').$post['address'];
            }

            if ($field) {
                \Phpcmf\Service::L('Field')->app(APP_DIR);
                // 验证数据
                list($save, $return, $attach) = \Phpcmf\Service::L('Form')->validation($post, null, $field);
                // 输出错误
                $return && $this->_json(0, $return['error'], ['field' => $return['name']]);
            }

            // 付款方式
            $pay_name = \Phpcmf\Service::L('input')->post('paytype');
            if (!$pay_type[$pay_name]) {
                $this->_json(0, dr_lang('付款方式不存在'));
            }
            // 优惠券
            // 获取运费
            // 计算付款价格
            // 按用户来拆分订单
            $users = [];
            foreach ($list as $t) {
                $users[$t['uid']][] = $t;
            }

            // 来自自定义字段和公共字段
            $field = [
                'uid' => $this->uid,
                'mid' => $this->module['dirname'],
                'username' => $this->uid ? $this->member['username'] : 'guest',
                'name' => (string)$post['name'],
                'phone' => (string)$post['phone'],
                'city' => (string)$post['city'],
                'address' => (string)$post['address'],
                'remark' => dr_safe_replace($post['remark']), // 订单备注
                'source' => $this->_get_agent_name(), // 来源
            ];
            if ($save[1]) {
                $field = array_merge($field, $save[1]);
            }

            $ids = [];
            foreach ($users as $uid => $item) {
                $total = 0;
                foreach ($item as $t) {
                    $total+= floatval($t['price']) * (int)$t['quantity'];
                }
                // 免费订单余额支付
                if (floatval($total) == 0) {
                    $pay_name = 'finecms';
                }
                $order = [
                    'sn' => $this->_get_order_sn(),
                    'money' => $total, //订单付款总金额
                    'pay_type' => $pay_name, // 付款方式
                    'sell_uid' => $t['uid'],
                    'sell_username' => $t['username'],
                ];
                $rt = \Phpcmf\Service::M('order', 'order')->checkout($order, $field, $item);
                !$rt['code'] && $this->_json(0, $rt['msg']);
                $ids[] = $rt['code'];
                // 附件归档
                if (SYS_ATTACHMENT_DB && $attach) {
                    \Phpcmf\Service::M('Attachment')->handle($order['uid'], \Phpcmf\Service::M()->dbprefix(SITE_ID.'_order-'.$rt['code']), $attach);
                }
            }

            if ($cart) {
                // 删除购物车记录
            }


            // 下单成功，跳转支付
            exit($this->_json(
                1, dr_lang('下单成功，正在跳转支付页面'), [
                    'url' => dr_url('order/order/pay', ['mid'=> $this->module['dirname'], 'id' => implode(',', $ids)])
                ]
            ));
        }

        \Phpcmf\Service::V()->assign([
            'list' => $list,
            'city' => dr_fieldform(array(
                'ismain' => 1,
                'name' => dr_lang('城市'),
                'fieldname' => 'city',
                'fieldtype' => 'Linkage',
                'setting' => array(
                    'option' => array(
                        'linkage' => 'address',
                    ),
                )
            ), (int)$this->address['city']),
            'myfield' => $field ? \Phpcmf\Service::L('Field')->app(APP_DIR)->toform(0, $field) : '',
            'address' => $this->address,
            'pay_type' => $pay_type,
            'pay_default' => $pay_default,
            'order_total' => $total,
            'is_address' => $this->config['module'][$this->module['dirname']]['shipping'],
            'meta_title' => dr_lang('订单结算').SITE_SEOJOIN.SITE_NAME,
            'meta_keywords' => $this->get_cache('site', SITE_ID, 'config', 'SITE_KEYWORDS'),
            'meta_description' => $this->get_cache('site', SITE_ID, 'config', 'SITE_DESCRIPTION')
        ]);
        \Phpcmf\Service::V()->display('checkout.html');
    }

    // 订单付款
    public function pay() {

        $str = dr_safe_replace(\Phpcmf\Service::L('input')->get('id'));
        if (!$str) {
            $this->_msg(0, dr_lang('订单参数不存在'));
        }

        $ids = explode(',', $str);
        $money = 0;
        $sn_str = $pay_type = '';
        foreach ($ids as $id) {
            $order = \Phpcmf\Service::M('order', 'order')->info($id);
            if (!$order) {
                $this->_msg(0, dr_lang('订单[%s]记录不存在', $id));
            } elseif ($order['status'] != 1) {
                $this->_msg(0, dr_lang('订单[%s]状态不正确', $order['sn']));
            }
            if (!$pay_type) {
                $pay_type = $order['pay_type'];
            }
            if ($pay_type != $order['pay_type']) {
                $this->_msg(0, dr_lang('订单[%s]支付方式不一样，无法合并付款', $order['sn']));
            }
            $money+= $order['money'];
            $sn_str.= $order['sn'].'、';
        }


        if ($money > 0) {
            // 创建支付
            $pay = [
                'mark' => 'orders-'.$pay_type.'-'.$str,
                'sn' => trim($sn_str, '、'),
                'uid' => $this->uid,
                'username' => $this->member['username'] ? $this->member['username'] : 'guest',
                'type' => $pay_type,
                'url' => dr_member_url('order/home/index'),
                'money' => $money,
            ];
            $rt = \Phpcmf\Service::M('pay')->post($pay);
            if (!$rt['code']) {
                $this->_msg(0, $rt['msg']);exit;
            }
            // 跳转到支付页面
            $url = ROOT_URL.'index.php?s=api&c=pay&id='.$rt['code'];
            dr_redirect($url, 'auto');
            exit;
        } else {
            // 免费订单，直接标志付款
            foreach ($ids as $id) {
                \Phpcmf\Service::M('order', 'order')->pay($this->uid, $id, 0);
            }
            exit($this->_json(
                1, dr_lang('订单付款成功'), [ 'url' => dr_member_url('order/home/index') ]
            ));
        }
    }


}
